package com.xjm_cloud_admin.controller;

import com.xjm_cloud_admin.annotation.Anonymous;
import com.xjm_cloud_admin.constant.CacheConstants;
import com.xjm_cloud_admin.domain.vo.req.EmailReqVo;
import com.xjm_cloud_admin.redis.RedisCache;
import com.xjm_cloud_admin.util.MailTemplateUtils;
import com.xjm_cloud_admin.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@Slf4j
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @PostMapping("/email")
    @Anonymous
    public R sendEmailCaptcha(@RequestBody EmailReqVo vo) {
        String qq = null;
        try {
            qq = vo.getEmail().substring(0, vo.getEmail().indexOf("@"));
        } catch (Exception e) {
            return R.error("邮箱格式错误");
        }
        String key = CacheConstants.MAIL_CODE_KEY + qq;
        Object object = redisCache.getCacheObject(key);
        if (object != null) {
            return R.error("验证码发送太频繁，请稍后再试");
        }
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //获取验证码
            String code = MailTemplateUtils.generatedcode(5);
            //创建简单邮件消息
            log.error("发送邮件开始，内容：{}，收件人：{}", code, vo.getEmail());
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发的
            helper.setFrom(from);
            //谁要接收
            helper.setTo(vo.getEmail());
            //邮件标题
            helper.setSubject("小鸡毛网盘验证码");
            //邮件内容
            helper.setText(MailTemplateUtils.buildContent(code), true);
            javaMailSender.send(message);
            log.error("发送邮件结束");
            //成功后存入redis
            redisCache.setCacheObject(key, code, 5, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            return R.success("邮件发送失败");
        }
        return R.success("邮件发送成功");
    }


}
